import { createRouter, createWebHashHistory } from 'vue-router';
import store from './store';
import menus from './utils/menus-config';

const redirect = { path: '/:pathMatch(.*)*', redirect: '/introduction' };
const recursiveFn = (arr) => arr.map((m) => [m, ...recursiveFn(m.children || [])]);
const routes = recursiveFn(menus).flat(3).filter(({ path }) => path).map(({ name, path, componentPath }) => ({
    name: path.replace('/', ''),
    path,
    component: () => import(`./${componentPath || 'views/index'}`),
    meta: {
        title: name,
    },
}));
routes.push(redirect);

const router = createRouter({
    history: createWebHashHistory(),
    routes,
});

router.beforeEach(async (to, from, next) => {
    window.NProgress.start();
    if (to.meta.title) document.title = to.meta.title;
    (document.getElementById('main-container') || {}).scrollTop = 0;
    store.commit('updateArticleTree', []);
    store.commit('updateCurrentLinkIndex', 0);
    next();
    window.NProgress.done();
});

export default router;
